<?php

namespace plugin\admin\app\model;

use app\services\GoodsService;
use plugin\admin\app\model\Base;

/**
 * @property integer $id (主键)
 * @property integer $level_id 用户等级ID
 * @property integer $goods_id 商品ID
 */
class UserCoupon extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'wa_user_coupons';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public static function getStatusText($coupon, array $categoryIds = [], $price = 0, $goodsIds = [])
    {
        if ($coupon['use_time']) {
            return [false, '已使用', 0];
        }

        if ($coupon['expiry_time'] < time()) {
            return [false, '已过期', 0];
        }

        $data = json_decode($coupon['data'], true);

        if (count($categoryIds) == 0) {
            return [false, '不适用的分类', 0];
        }

        if ($data['goods_category_ids']) {
            $goodsCategoryIds = explode(',', $data['goods_category_ids']);

            if (count(array_intersect($categoryIds, $goodsCategoryIds)) == 0) {
                return [false, '不适用的分类', 0];
            }
        }

        if ($data['only_for_gift']) {
            if (!GoodsService::isGift($goodsIds[0])) {
                return [false, '仅限报单产品使用', 0];
            }
        }

        if ($price >= $data['full']) {
            return [true, '可用', $data['reduce']];
        } else {
            return [false, '未达到门槛金额', 0];
        }


    }

    public static function getStatus($coupon, $userCoupon)
    {
        if ($coupon['total_count'] > 0 && $coupon['receive_count'] >= $coupon['total_count']) {
            return [-1, '已领完'];
        }

        if (is_null($userCoupon)) {
            return [0, '未领取'];
        }

        if ($userCoupon['use_time']) {
            return [2, '已使用'];
        }

        if ($userCoupon['expiry_time'] < time()) {
            return [3, '已过期'];
        }

        return [1, '已领取'];
    }
    
}
